import axios, {AxiosError, AxiosResponse, InternalAxiosRequestConfig} from "axios";
import Cookies from "js-cookie"
import {message} from "antd";
import {filterParams} from "../util";

// 实例
const request = axios.create({
    timeout: 10000,
});
const token = Cookies.get("token");

export interface ResponseType {
    code: number,
    data: any,
    message: string
}

// 请求拦截
request.interceptors.request.use((config: InternalAxiosRequestConfig | any) => {
    if (config?.url !== '/api/pc/user/register' && config?.url !== '/api/pc/user/login') {
        if (!token) {
            return window.location.href = "/login";
        }
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    // 创建取消请求实例
    const cancelTokenSource = axios.CancelToken.source();
    config.cancelTokenSource = cancelTokenSource;
    // 配置取消请求token
    config.cancelToken = cancelTokenSource.token;
    // 过滤无用的参数值，包含null和undefined
    config.data = filterParams(config.data);
    return config
})
// 响应拦截
request.interceptors.response.use(
    (res: AxiosResponse) => {
        if (res?.data?.code !== 1) {
            message.error(res?.data?.message);
            if (res?.data?.code === -1) {
                window.location.href = "/login";
            }
            return Promise.resolve(res?.data);
        }
        return Promise.resolve(res);
    },
    (err: AxiosError) => {
        if (axios.isCancel(err)) {
            message.info('请求已取消')
        }
        return new Promise(() => message.error(err?.response?.data as string))
    });

// 请求取消
export const rqCancelHandle = (config: InternalAxiosRequestConfig | any) => {
    if (config && config.cancelTokenSource) {
        config.cancelTokenSource.cancel()
    }
}


export default request;

